iT邦幫忙

2022 iThome 鐵人賽

DAY 19
0
Mobile Development

Android studio 30天新手筆記系列 第 19

Day19-Android新手筆記-Retrofit使用與天氣API連線

  • 分享至 

  • xImage
  •  

/images/emoticon/emoticon31.gif

取得中央氣象局-氣象開放資料平台API授權碼

註冊中央氣象局-氣象會員

https://opendata.cwb.gov.tw/userLogin
https://ithelp.ithome.com.tw/upload/images/20220720/20150372Om4Mkl3ywd.png

註冊完成後,登入會看到API授權碼畫面

點擊獲取API授權碼按鈕,API授權碼會出現於右側
https://ithelp.ithome.com.tw/upload/images/20220720/201503724vGgnaE1qy.png
https://ithelp.ithome.com.tw/upload/images/20220720/20150372L2IPaw5M3Q.png

進入中央氣象局開放資料平臺

https://opendata.cwb.gov.tw/dist/opendata-swagger.html#/%E6%B0%A3%E5%80%99/get_v1_rest_datastore_C_B0025_001

往下滑找到 每日雨量-局屬地面測站每日雨量資料

點擊右側Try it out按鈕,並輸入API授權碼

https://ithelp.ithome.com.tw/upload/images/20220720/2015037270iZ4qeLqh.png
https://ithelp.ithome.com.tw/upload/images/20220720/20150372mSrfTUBxS8.png

點擊Execute按鈕,顯示結果

紅框內的URL是我們要注意的重點
https://ithelp.ithome.com.tw/upload/images/20220720/20150372UoAuIsR6F1.png

Retrofit

進入Gradle加入retrofit2:retrofit與retrofit2:converter-gson

    //retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

進入AndroidManifet.xml加入網路權限

<uses-permission android:name="android.permission.INTERNET"/>

建立 RetrofitManager 、 APIService 與 APIAuthorize

RetrofitManager

/**
 *
 * 本局所屬地面測站每日雨量資料-每日雨量
 * https://opendata.cwb.gov.tw/api/v1/rest/datastore/C-B0025-001?Authorization=CWB-F466F13C-84CD-4A6E-81CB-F3ED6C48A773
 *
 * 月平均-局屬地面測站資料
 * https://opendata.cwb.gov.tw/api/v1/rest/datastore/C-B0027-001?Authorization=CWB-F466F13C-84CD-4A6E-81CB-F3ED6C48A773
 *
 * 氣象測站基本資料-有人氣象測站基本資料
 * https://opendata.cwb.gov.tw/api/v1/rest/datastore/C-B0074-001?Authorization=CWB-F466F13C-84CD-4A6E-81CB-F3ED6C48A773
 *
 * 把重複的URL 設在 baseUrl
 * https://opendata.cwb.gov.tw/api/v1/rest/datastore/
 *
 **/

public class RetrofitManager {
    private static RetrofitManager mInstance = new RetrofitManager();
    private APIService apiService;
    private RetrofitManager() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://opendata.cwb.gov.tw/api/v1/rest/datastore/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        apiService = retrofit.create(APIService.class);
    }
    //向外提供 RetrofitManager
    public static RetrofitManager getInstance() {
        return mInstance;
    }
    //向外提供 APIService
    public APIService getAPI() {
        return apiService;
    }
}

APIService

/**
 *
 * 把重複的URL 設在 baseUrl
 * https://opendata.cwb.gov.tw/api/v1/rest/datastore/
 *
 * 不重複的URL 設在 @GET 或 @POST 後方
 * @GET("C-B0025-001?")
 *
 **/
 public interface APIService {
    @GET("C-B0025-001?")
    Call<DataResponse> getDailyRainfall(@Query("Authorization") String Authorization);
 }

這邊的DataResponse如果是紅色請不要緊張,因為我們還沒建立這個檔案。

APIAuthorize

public class APIAuthorize {
    //這邊請替換為申請的授權碼
    private final String Authorization = "CWB-F466F13C-84CD-4A6E-81CB-F3ED6C48A773";
    //向外提供授權碼
    public String getAuthorization() {
        return Authorization;
    }
}

建立Response

根據中央氣象局開放資料平臺Execute後的結果,請找到Response body如下:

這邊建立以下幾個檔案,來做為接收API的格式:

  • DataResponse
/**
 * 中括號要用List,大括號則用Class
 **/
public class DataResponse {
    @SerializedName("records")
    private Records records;

    public DataResponse(Records records) {
        this.records = records;
    }

    public Records getRecords() {
        return records;
    }

    public void setRecords(Records records) {
        this.records = records;
    }
}
  • Records
public class Records {
    private List<Location> location = new ArrayList<>();
    //Records中包了Location
    //這邊使用List的原因是因為被中括號包起來
    public Records(List<Location> location){
        this.location = location;
    }

    public List<Location> getLocation() {
        return location;
    }

    public void setLocation(List<Location> location) {
        this.location = location;
    }
}
  • Location
public class Location {
    private Station station;
    private StationObsTimes stationObsTimes;
    //Location中包了Station與StationObsTimes
    public Location(Station station, StationObsTimes stationObsTimes) {
        this.station = station;
        this.stationObsTimes = stationObsTimes;
    }

    public Station getStation() {
        return station;
    }

    public StationObsTimes getStationObsTimes() {
        return stationObsTimes;
    }
}
  • Station
public class Station {
    private String stationID;
    private String stationName;
    private String stationNameEN;
    private String stationAttribute;
    
    public Station(String stationID, String stationName, String stationNameEN, String stationAttribute) {
        this.stationID = stationID;
        this.stationName = stationName;
        this.stationNameEN = stationNameEN;
        this.stationAttribute = stationAttribute;
    }

    public String getStationID() {
        return stationID;
    }

    public String getStationName() {
        return stationName;
    }

    public String getStationNameEN() {
        return stationNameEN;
    }

    public String getStationAttribute() {
        return stationAttribute;
    }
}
  • StationObsTimes
public class StationObsTimes {
    private List<StationObsTime> stationObsTime;
    //StationObsTimes中包了StationObsTime
    //這邊使用List的原因是因為被中括號包起來
    public StationObsTimes(List<StationObsTime> stationObsTime) {
        this.stationObsTime = stationObsTime;
    }

    public List<StationObsTime> getStationObsTime() {
        return stationObsTime;
    }
}
  • StationObsTime
public class StationObsTime {
    private String dataDate;
    private WeatherElements weatherElements;

    public StationObsTime(String dataDate,WeatherElements weatherElements) {
        this.dataDate = dataDate;
        this.weatherElements = weatherElements;
    }

    public String getDataDate() {
        return dataDate;
    }

    public WeatherElements getWeatherElements() {
        return weatherElements;
    }
}
  • WeatherElements
public class WeatherElements {
    private String precipitation;
    public WeatherElements(String precipitation) {
        this.precipitation = precipitation;
    }

    public String getPrecipitation() {
        return precipitation;
    }
}

接下來回到 MainActivity,進行連線、資料獲取。

public class MainActivity extends AppCompatActivity {
    APIService apiService;
    APIAuthorize apiAuthorize = new APIAuthorize();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        apiService = RetrofitManager.getInstance().getAPI();
        
        Call<DataResponse> call = apiService.getDailyRainfall(apiAuthorize.getAuthorization());
        
        //連線API,獲取資料
        call.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                // 連線成功
                // 取得回傳資料
                Log.d("TESTTEST","precipitation:" + response.body().getRecords()
                        .getLocation()
                        .get(0).getStationObsTimes()
                        .getStationObsTime()
                        .get(0).getWeatherElements()
                        .getPrecipitation());
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                // 連線失敗
                Log.e("test",t.toString());
            }
        });
    }
}

結果如下:
https://ithelp.ithome.com.tw/upload/images/20220721/20150372isOKrif0iv.png

/images/emoticon/emoticon41.gif


上一篇
Day18-Android新手筆記-RecyclerView滑動刪除與上下拖曳
下一篇
Day20-Android新手筆記-使用Room資料庫搭配Rxjava
系列文
Android studio 30天新手筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言